package com.wanmei.controller.user;

import com.wanmei.exception.WanmeiException;
import com.wanmei.pojo.Exception_Msg;
import com.wanmei.pojo.JsonResult;
import com.wanmei.pojo.User;
import com.wanmei.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 找回密码
     *
     * @return
     */
    @RequestMapping("/info/findPassword.do")
    public String findPassword() {
        return "email_findPassword";
    }

    /**
     * 注册
     *
     * @return
     */
    @RequestMapping("/info/register.do")
    public String registerMethod() {
        return "register";
    }


    /**
     * 校验用户名时候存在
     */
    @RequestMapping("/info/check_name.json")
    @ResponseBody
    public JsonResult checkUsername(@RequestParam("username") String username) {
        JsonResult result = new JsonResult();
        int count = userService.checkUsernameByUsername(username);
        if (count > 0) {
            result.setCode(0);
            result.setMsg("该用户名已经存在！");
        } else {
            result.setCode(1);
        }
        return result;
    }

    /**
     * 注册请求
     */
    @RequestMapping("/info/register.json")
    @ResponseBody
    public JsonResult registerSuccess(User user, HttpServletRequest req) throws WanmeiException {
        JsonResult result = new JsonResult();
        String inCode = req.getParameter("captchaCode");
        String rePassword = req.getParameter("rePassword");
        String sessionCode = (String) req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        if (inCode == null || inCode == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100010);
        }
        if (!inCode.equals(sessionCode)) {
            throw new WanmeiException(Exception_Msg.ERROR_100011);
        }
        int isSuccess = userService.insertUserInfo(user, rePassword);
        if (isSuccess == 1) {
            result.setCode(1);
            result.setMsg("注册成功！");
        } else {
            result.setMsg("注册失败！");
        }
        return result;
    }


}

